package com.kgc.controller;

import com.alibaba.fastjson.JSON;
import com.kgc.constant.WxpayConstant;
import com.kgc.service.impl.WxpayService;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：周申宇 <p>
 * @Date:2021/6/16 14:24
 * <p>
 * @Decription:  微信支付入口
 */
@RestController
@Api(tags = "微信支付")
@Slf4j
@RequestMapping("/wxpay")
public class WxpayController extends BaseController{

    @Autowired
    private WxpayService wxpayService;
    /**
     * @Auther: 周申宇
     * <p>
     * @Date: 2021/6/16
     * <p>
     * @Description: 调用微信官方统一下单
     */
    @ApiOperation("微信支付订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderInfoId",required = true,value = "订单编号"),
            @ApiImplicitParam(name = "body",required = true,value = "商品描述"),
            @ApiImplicitParam(name = "total_fee",required = true,value = "总价")
    })
    @ApiResponses({
            @ApiResponse(code = 4001,message = "参数错误"),
            @ApiResponse(code = 1001,message = "请重新登录"),
            @ApiResponse(code = 0000,message = "访问成功")
    })
    @PostMapping("/wxpayOrder")
    public ReturnResult<Map<String,String>> wxpayOrder(
            HttpServletRequest request,
            @RequestParam("orderInfoId")String orderInfoId,
            @RequestParam("body") String body ,
            @RequestParam("total_fee") Integer total_fee)throws Exception{

        // 封装统一下单接口参数字符串
        String wxpayOrderStr = wxpayService.getWxpayOrderParamsXmlStr(orderInfoId,body,this.getRemoteIp(request),total_fee);
        log.info("------ 发送微信统一下单参数{} ",wxpayOrderStr);
        // 调用微信统一下单接口
        Map<String,String> wxpayOrderReturnMap = wxpayService.send2WxpayUnifieldOrder(wxpayOrderStr);
        log.info("------ 发送微信统一下单返回结果：{}",wxpayOrderReturnMap);

        // 统一返回下单结果
        Map<String,String> wxReturnData = new HashMap<>();
        // 解析map
        if(WxpayConstant.WXPAY_RETURN_SUCCESS.equals(wxpayOrderReturnMap.get("return_code"))
            && WxpayConstant.WXPAY_RETURN_OK.equals(wxpayOrderReturnMap.get("return_msg"))){
            wxReturnData.put("trade_type",wxpayOrderReturnMap.get("trade_type"));
            wxReturnData.put("prepay_id",wxpayOrderReturnMap.get("prepay_id"));
            wxReturnData.put("code_url",wxpayOrderReturnMap.get("code_url"));
        }

        return ResultBuildUtil.success(wxReturnData);
    }

    /**
     * @Auther: 周申宇
     * <p>
     * @Date: 2021/6/16
     * <p>
     * @Description: 微信支付结果异步回调入口
     */
    @PostMapping("/wxpayNotify")
    public void wxpayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 解析微信官方支付结果返回回调内容
        StringBuffer sbf = new StringBuffer();

        // 微信异步处理结果
        String wxpayNotifyStr = "";

        // 微信官方返回是数据流
        try (InputStream inputStream = request.getInputStream()){
            // 高效读取
            BufferedReader bfr = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));

            String line;
            while ((line = bfr.readLine()) != null){
                sbf.append(line);
            }

            log.info("------ ++ 微信异步回调支付结果：{}",sbf.toString());
            wxpayNotifyStr = wxpayService.resolveWxpayOrderNotify(sbf.toString());


        }catch (IOException e){
            log.error("微信解析异常：{}",e.getMessage());
        }

        //结果解析成功，同比返回微信返回结果
        PrintWriter out =response.getWriter();
        out.write(wxpayNotifyStr);
        out.flush();
        out.close();

    }
}
